/**
 *  Module
 *
 * Description
 */
angular
    .module('sfhtHaitaoCmsApp')
    .config(function( $compileProvider ) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|data):/);
        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|data):/);
      }
    )
    .controller('ModuleCommonCtrl', function($rootScope, $route, $injector, $q, $scope, $routeParams, $modal, $filter, ModuleDataStore) {
        var commonBizService = $injector.get("CommonBiz");
        var empty = function() {
            console.log(arguments);
        }

        /**
         * 增加属性
         * @param  {object} 属性对象
         * @param  {string} 属性名称
         * @param  {string} 属性描述
         * @param  {string} 属性值
         * @return {array}
         */
        function addProperty(properties, fieldName, fieldDesc, value) {
            properties.push({
                'field': {
                    'fieldName': fieldName,
                    'fieldType': 'String',
                    'fieldDesc': fieldDesc
                },
                'propertyName': fieldName,
                'propertyValue': value
            });
        }

        //根据属性列表查找属性
        function findProperty(properties, propertyName) {
            return _.findWhere(properties, {
                propertyName: propertyName
            });
        }

        /**
         * 根据时间获取产品数据的状态
         * @param  {array} 产品数据
         * @return {array}
         */
        function getProductstatus(dataList, index) {
            _.each(dataList, function(cmsData, ckey, dataValue) {
                var starttime = findProperty(cmsData.properties, 'startTime');
                var endtime = findProperty(cmsData.properties, 'endTime');
                if (starttime && endtime) {
                    if (starttime.propertyValue > new Date()) {
                        $scope.mainproducts[index].cmsData[ckey].parseStatus = "default"
                    } else if (starttime.propertyValue < new Date() && endtime.propertyValue > new Date()) {
                        $scope.mainproducts[index].cmsData[ckey].parseStatus = "success"
                    } else {
                        $scope.mainproducts[index].cmsData[ckey].parseStatus = "danger"
                    }
                }
                _.each(cmsData.properties, function(property, key, list) {
                    if (property.field.fieldType == 'Date') {
                        var date = parseInt($scope.mainproducts[index].cmsData[ckey].properties[key].propertyValue)
                        $scope.mainproducts[index].cmsData[ckey].properties[key].propertyValue = new Date(date);
                    }
                });
            });
        }


        /**
         * 查询模块数据列表
         * @param  {int} 页面id
         * @param  {string} 模块名称
         * @param  {function} 后续处理函数
         * @return {array}
         */
        var getDataList = function(pageId, placeHolder, fn) {
            commonBizService.getDataList(pageId, placeHolder)
                .then(function(data) {
                    $scope.mainproducts = data.value;
                    _.each($scope.mainproducts, function(mainproducts, index, value) {
                        var deferred = $q.defer();
                        try {
                            if (mainproducts && mainproducts.cmsData) {
                                //查询库存
                                var isItemList = mainproducts ? findProperty(mainproducts.cmsData[0].properties, 'itemId') : false;
                                if (isItemList) {
                                    commonBizService.getItems({
                                            'searchKeywords': 'list:' + mainproducts.listId
                                        })
                                        .then(function(itemInfos) {
                                            deferred.resolve(itemInfos);
                                            _.each(mainproducts.cmsData, function(cmsData, ckey, dataValue) {
                                                var itemId = findProperty(cmsData.properties, 'itemId').propertyValue;
                                                if (itemId != "undefined" && itemId != "0") {
                                                    var iteminfoValue = _.findWhere(itemInfos.value, {
                                                        'itemId': itemId
                                                    });
                                                    addProperty(mainproducts.cmsData[ckey].properties, '_stock', '剩余库存', iteminfoValue == null ? "" : iteminfoValue.stock);
                                                    addProperty(mainproducts.cmsData[ckey].properties, '_price', '当前售价', iteminfoValue == null ? "" : iteminfoValue.price);
                                                    addProperty(mainproducts.cmsData[ckey].properties, '_status', '产品状态', iteminfoValue == null ? "" : iteminfoValue._status);
                                                }
                                            });
                                        }, function(data) {
                                            deferred.reject(data);
                                        });
                                } else {
                                    deferred.resolve();
                                }
                            } else {
                                deferred.resolve();
                            }
                        } catch (e) {
                            console.log(e);
                            deferred.resolve();
                        }
                        //end
                        deferred.promise.then(function(data) {
                            getProductstatus(mainproducts.cmsData, index);
                        });
                    }, empty);
                    if (fn) {
                        fn();
                    }
                }, empty);
        };

        //根据条件排序
        function sortProductData(items, index, descValue, propertyName) {
            $scope.mainproducts[index].cmsData = _.sortBy(items, function(item) {
                var found = findProperty(item.properties, propertyName);
                return descValue * parseInt(found.propertyValue);
            });
        }

        /**
         * 查询模块数据的详细列表
         * @param  {function} 后续处理函数
         * @return {array}
         */
        var getModuleDetail = function(fn) {
            commonBizService.getModuleDetail($routeParams.moduleName, $routeParams.pageType, false)
                .then(function(data) {
                    $scope.module = data;
                    if (fn) {
                        fn();
                    }
                }, function(data) {
                    console.log(data);
                });
        };

        $scope.getSubModuleName = function(submoduleId) {
            return _.findWhere($scope.module.cmsSubModuleList, {
                'id': submoduleId
            }).description;
        };
        $scope.init = function() {
            $scope.pageId = $routeParams.pageid;
            $scope.pageType = $routeParams.pageType;
            $scope.placeholder = $routeParams.placeholder;
            getModuleDetail(function() {
                getDataList($routeParams.pageid, $routeParams.placeholder, function() {
                    initTabs();
                });
            });
            /**
             * 查询国家列表
             * @param
             * @return {array}
             */
            commonBizService.getNations($scope)
                .then(function(data) {
                    $scope.nations = data.value;
                });
            // /**
            //  * 查询权重配置字段
            //  * @param
            //  * @return {array}
            //  */
            // commonBizService.getWeightConfigFields()
            //     .then(function(data) {
            //         $scope.weightConfigFields = data.value;
            //     });
        };
        //过滤展示数据
        $scope.filerShowProperties = function(properties) {
            var result = [];
            if (properties) {
                var count = 0;
                for (var index = 0; index < properties.length && count < 3; index++) {
                    if (properties[index].field.fieldType == 'Date') {
                        result.push(properties[index]);
                        count++;
                    }
                }
                for (var index = 0; index < properties.length && count < 3; index++) {
                    var temp = properties[index];
                    if (temp.field.fieldName != 'imgUrl' && temp.field.fieldType != 'Html' && temp.field.fieldType != 'Date') {
                        result.push(temp);
                        count++;
                    }
                }
            }
            return result;
        };
        $scope.getDate = function(timestamp) {
            return new Date(timestamp)
        };

        //是否存在图片
        $scope.hasImg = function(properties) {
            return properties && findProperty(properties, "imgUrl");
        };
        //解析图片
        $scope.parseImg = function(properties) {
            if (properties) {
                var temp = findProperty(properties, "imgUrl");
                if (temp) {
                    return temp.propertyValue;
                }
            }
        };
        //判断是否是商品列表
        $scope.isItem = function(submoduleId, item) {
            var submodule = _.findWhere($scope.module.cmsSubModuleList, {
                'id': submoduleId
            });
            return _.findWhere(submodule.showFields, {
                'fieldName': 'itemId'
            }) ;
        };

        $scope.showSearch = function(submoduleId, item){
            return $scope.isItem(submoduleId, item) || ($routeParams.placeholder.indexOf("HotKeyWords") > -1);
        };

        //是否售罄
        $scope.getStatusOfItem = function(info) {
            if (info) {
                var statusProperty = findProperty(info, "_status");
                if (statusProperty) {
                    return statusProperty.propertyValue;
                }
            }
            return 0;
        };

        //查询info信息中属性Wieproperty的值
        $scope.getItemInfoValue = function(info, property) {
            if (info) {
                var stockProperty = findProperty(info, property);
                if (stockProperty) {
                    return stockProperty.propertyValue;
                }
            }
        };

        // //获取货值
        // $scope.getItemtotalValue = function(info) {
        //     if (info) {
        //         var stockProperty = findProperty(info, "_stock");
        //         var price = findProperty(info, "_price");
        //         if (stockProperty && price) {
        //             return stockProperty.propertyValue * price.propertyValue;
        //         }
        //     }
        // };

        $scope.pricesort = "default"; //asc desc

        //按价格排序
        $scope.sortByPrice = function(items, index) {
            var descValue = $scope.pricesort == "desc" ? 1 : -1;
            $scope.pricesort == "desc" ? $scope.pricesort = "asc" : $scope.pricesort = "desc"
            sortProductData(items, index, descValue, "_price");
        };
        //根据库存排序
        $scope.stocksort = "default"; //asc desc
        $scope.sortByStock = function(items, index) {
            var descValue = $scope.stocksort == "desc" ? 1 : -1;
            $scope.stocksort == "desc" ? $scope.stocksort = "asc" : $scope.stocksort = "desc"
            sortProductData(items, index, descValue, '_stock');
        };
        /**
         * 智能排序
         * @param  {[type]} items [description]
         * @param  {[type]} index [description]
         * @return {[type]}       [description]
         */
        $scope.smartSort = function(items, index) {
            var weightConfigs = [];
            _.each($scope.weightConfigFields, function(field) {
                weightConfigs.push({
                    'key': field.key,
                    'value': field.weightValue
                });
            });
            commonBizService.smartSort(items, weightConfigs).then(function(data) {
                $scope.mainproducts[index].cmsData = data.value;
            });
        };
        /**
         * 模块数据排序
         * @param
         * @return {array}
         */
        $scope.saveAll = function($event) {
            $event.preventDefault();
            // $scope.mainproducts.pageId = $routeParams.pageid;
            $scope.mergeTab();
            commonBizService.updateAllCmsData($scope.mainproducts)
                .then(function(data) {
                    alert("保存成功!");
                }, function(data) {
                    alert("Error: " + data);
                });
        };

        /**
         * 删除模块数据
         * @param  {object} 删除对象
         * @param  {string} 搜索关键词
         * @return {array}
         */
        $scope.deleteProduct = function(item, $event) {
            $event && $event.preventDefault();
            if (window.confirm("确定要删除数据吗？")) {
                commonBizService.deleteData($scope, item)
                    .then(function(data) {
                        if (data) {
                            if ($scope.mainproducts && $scope.mainproducts.length > 0) {
                                _.each($scope.mainproducts, function(product, index) {
                                    $scope.mainproducts[index].cmsData = _.reject(product.cmsData, function(items) {
                                        return items.id == item.id;
                                    });
                                });
                            } else {
                                $scope.mainproducts.cmsData = _.reject($scope.mainproducts.cmsData, function(items) {
                                    return items.id == item.id;
                                });
                            }
                        }
                    }, function(data) {
                        alert("Error: " + data);
                    });
                $scope.deleteFromTabMaps(item);
            }
        };

        /**
         * 批量删除数据
         * @param  {[type]} cmsDatas [description]
         * @return {[type]}          [description]
         */
        var bantchDelete = function(datas) {
            if (datas && datas.length > 0) {
                commonBizService.bantchDeleteCmsData(datas)
                    .then(function(data) {
                        $route.reload();
                        // window.location.reload(true);
                    }, function(data) {
                        alert("删除失败，" + data);
                    });
            }
        };

        //根据属性名过滤符合条件的数据，type为类型的判断条件
        function getCmsDatas(cmsDatas, propertyName, fn) {
            var datas = [];
            var now = new Date();
            _.each(cmsDatas, function(value, key, list) {
                var property = findProperty(value.properties, propertyName);
                if (property && fn && fn(property.propertyValue)) {
                    datas.push(value);
                }
            });
            return datas;
        }

        /**
         * 删除售罄商品
         * @param  {[type]} cmsDatas [description]
         * @return {[type]}          [description]
         */
        $scope.deleteSoldOut = function(cmsDatas) {
            bantchDelete(getCmsDatas(cmsDatas, "_status", function(value) {
                return value != 0;
            }));
        };
        /**
         * 删除过期数据
         * @param  {[type]} cmsDatas [description]
         * @return {[type]}          [description]
         */
        $scope.deleteExpire = function(cmsDatas) {
            bantchDelete(getCmsDatas(cmsDatas, "endTime", function(value) {
                return value < new Date();
            }));
        };

        $scope.checkAll = function(cmsDatas, index) {
            _.each(cmsDatas, function(value, key, list) {
                $scope.mainproducts[index].allChecked ? value.checked = true : value.checked = false;
            });
        };
        /**
         * 批量删除数据
         * @param  {[type]} cmsDatas [description]
         * @return {[type]}          [description]
         */
        $scope.bantchDeleteCmsData = function(cmsDatas) {
            var datas = _.filter(cmsDatas, function(value) {
                return value.checked == true;
            });
            bantchDelete(datas);
        };
        /**
         * 发布数据
         */
        $scope.publishData = function() {
            if (window.confirm("确认发布?")) {
                commonBizService.publishData($scope.pageId, $scope.placeholder)
                    .then(function(data) {
                        $route.reload();
                        // window.location.reload(true);
                    }, function(data) {
                        alert("发布失败!" + data);
                    });
            }
        };
        /**
         * 还原数据
         */
        $scope.revert = function() {
            if (window.confirm("还原至上一个发布版本?")) {
                commonBizService.revert($scope.pageId, $scope.placeholder)
                    .then(function(data) {
                        $route.reload();
                        // window.location.reload(true);
                    }, function(data) {
                        alert("还原失败!" + data);
                    });;
            }
        };
        /**
         *打开专题页地址
         **/
        $scope.viewOnline = function() {
            commonBizService.getAccessURL($scope.pageId)
                .then(
                    function(data) {
                        window.open(data.value);
                    }
                );
        };
        //查询模块中数据的详细信息，并且展现出来
        $scope.openDataDetail = function(item, $event) {
            $event.preventDefault();
            var modal = $modal.open({
                animation: true,
                templateUrl: 'modal.data.info.html',
                controller: 'ModalDataCtrl',
                size: 'lg',
                resolve: {
                    item: function() {
                        return item;
                    },
                    nations: function() {
                        return $scope.nations;
                    }
                }
            });
            modal.result.then(function(data) {
                item.version = data.value;
            }, empty);
        };

        //查询模块中数据的详细信息，并且展现出来
        $scope.addDataDetail = function($event, submoduleId, listId, tabId) {
            $event.preventDefault();
            commonBizService.getFieldOfSubModule(submoduleId)
                .then(function(data) {
                    var modal = $modal.open({
                        animation: true,
                        templateUrl: 'modal.data.add.html',
                        controller: 'ModalAddDataCtrl',
                        size: 'lg',
                        resolve: {
                            //data属性字段
                            item: function() {
                                return data.value;
                            },
                            listId: function() {
                                return listId;
                            },
                            nations: function() {
                                return $scope.nations;
                            },
                            tabId: function() {
                                return tabId;
                            }
                        }
                    });
                    modal.result.then(empty, empty);
                });
        };
        //复制列表 todo copy for tab
        $scope.copyDataDetail = function(listId, tabId) {
            var modal = $modal.open({
                animation: true,
                templateUrl: 'modal.data.copy.html',
                controller: 'ModalCopyDataCtrl',
                size: 'lg',
                resolve: {
                    targetListId: function() {
                        return listId;
                    },
                    tabId: function() {
                        return tabId;
                    },
                    pageId: function() {
                        return $routeParams.pageid;
                    },
                    placeHolder: function() {
                        return $routeParams.placeholder;
                    }
                }
            });
            modal.result.then(empty, empty);
        };
        //搜索商品
        $scope.searchProduct = function(listId, $event, tabId) {
            $event.preventDefault();
            var submoduleInfo = null;
            var modal = $modal.open({
                animation: true,
                templateUrl: 'modal.product.addProduct.html',
                controller: 'ModalAddProductInfoCtrl',
                size: 'lg',
                resolve: {
                    listId: function() {
                        return listId;
                    },
                    tabId: function() {
                        return tabId;
                    }
                }
            });
            modal.result.then(empty, empty);
        };
        //搜索商品
        $scope.bantchUpdateData = function(cmsDatas, submoduleId) {
            var submoduleInfo = null;
            var datas = _.filter(cmsDatas, function(value) {
                return value.checked == true;
            });
            if (!datas || datas.length == 0) {
                alert("请先选择需修改的数据");
                return;
            }
            commonBizService.getFieldOfSubModule(submoduleId)
                .then(function(data) {
                    var modal = $modal.open({
                        animation: true,
                        templateUrl: 'modal.data.bantchupdatedata.html',
                        controller: 'ModalBantchUpdateDataCtrl',
                        size: 'lg',
                        resolve: {
                            fields: function() {
                                return data.value;
                            },
                            cmsDatas: function() {
                                return datas;
                            },
                            nations: function() {
                                return $scope.nations;
                            }
                        }
                    });
                    modal.result.then(empty, empty);
                });
        };
        //日历控件默认选中时间
        $scope.time = new Date().getTime();
        //tab相关操作
        $scope.tabMaps = {};
        $scope.tabs = {};
        /**
         * tab标签初始化
         * @return {[type]} [description]
         */
        var initTabs = function() {
            _.each($scope.mainproducts, function(value) {
                if (_.findWhere(_.findWhere($scope.module.cmsSubModuleList, {
                        'id': value.submoduleId
                    }).showFields, {
                        'fieldName': 'tag'
                    }) && value.processorName != 'tabItemListProcessor') {
                    $scope.tabs = value.cmsData;
                    _.each($scope.tabs, function(tabvalue) {
                        //tab标签名称
                        tabvalue._name = findProperty(tabvalue.properties, "name").propertyValue;
                        //tab标签ID
                        tabvalue._tag = findProperty(tabvalue.properties, "tag").propertyValue;
                    });
                }
            });
            var selectedTab = ModuleDataStore.get("selectedTab");
            if (selectedTab) {
                _.each($scope.tabs, function(tab) {
                    if (tab._tag == selectedTab._tag) {
                        tab.active = true;
                    }
                })
            };
        };

        $scope.filterByTab = function(list, tabId) {
            var tabMap = $scope.tabMaps[list.listId];
            if (!tabMap) {
                tabMap = {};
            }
            tabMap[tabId] = $filter('filter')(list.cmsData, tabId);
            $scope.tabMaps[list.listId] = tabMap;
        };

        /**
         * 将tab分组后的数据重新合并
         */
        $scope.mergeTab = function() {
            _.each($scope.mainproducts, function(value, key, list) {
                if ($scope.tabMaps[value.listId]) {
                    list[key].cmsData = [];
                    _.each($scope.tabMaps[value.listId], function(lvalue, tkey) {
                        _.each(lvalue, function(tvalue, tkey) {
                            list[key].cmsData.push(tvalue);
                        });
                    });
                }
            });
        };
        /**
         * 删除tab，触发刷新
         */
        $scope.deleteFromTabMaps = function(item) {
            if (findProperty(item.properties, "tag")) {
                $route.reload();
                // window.location.reload(true);
            }
        };
        $scope.checkAllInTabMap = function(cmsDatas, listId, tabId) {
            _.each(cmsDatas, function(value, key, list) {
                $scope.tabMaps[listId][tabId].allChecked ? value.checked = true : value.checked = false;
            });
        };
        /**
         *tab选中
         **/
        $scope.storeSelectedTab = function(tab) {
            ModuleDataStore.set("selectedTab", tab);
        };


        //批量拖拽
        $scope.itemDrag = function(itemList, index, item, event, products){
            if(item.checked){
                var num = 0;
                var checkedItemIndex = [];
                var items = [];
                var batchDrag = false;
                _.find(itemList, function(itemTemp, $index){
                    if(itemTemp.itemId && itemTemp.itemId == item.itemId){
                        num = $index;
                        batchDrag = true;
                    }
                });

                if(batchDrag){
                   _.each($scope.items, function(item){
                        _.find(itemList, function(temp, $index){
                            if(temp.itemId == item.itemId){
                                checkedItemIndex.push($index);
                            }
                        });
                    });

                    _.each(itemList, function(itemTemp, $index){
                        if(num == $index){
                            pushItems(itemList, items, checkedItemIndex);
                        }else if(!containsItem(checkedItemIndex, $index)){
                            items.push(itemTemp);
                        }
                    });

                    for(var i = 0; i < $scope.mainproducts.length; i++){
                        if(products == $scope.mainproducts[i]){
                            $scope.mainproducts[i].cmsData = items;
                        }
                    }
                }
            }
        };

        $scope.dragStart = function(itemList){
            var items = [];
             _.each(itemList, function(itemTemp, $index){
                if(itemTemp.checked){
                    items.push(itemTemp);
                }
            });
             $scope.items = items;
        };
        function containsItem(items, value){
            var temp = _.filter(items, function(item){ return item == value;});
            if(temp && temp.length > 0){
                return true;
            }
            return false;
        }

        function pushItems(items, itemList, indexList){
            for(var i = 0, size = indexList.length; i < size; i++){
                itemList.push(items[indexList[i]]);
            }
        }

        $scope.getItemIds = function(products){
            var items = [];
            _.each(products.cmsData, function(item){
                items.push(item.itemId);
            });
            return "" + items.join(",");
        };
    });
